from flask import Blueprint, render_template
from flask_socketio import SocketIO, emit, join_room, leave_room

# 创建聊天蓝图
chat_blue = Blueprint('chat', __name__)

# 创建 SocketIO 实例
socketio = SocketIO()


# 在聊天蓝图中定义 WebSocket 事件处理程序
@chat_blue.route('/chat', methods=['GET'])
def chat():
    return render_template('chat.html')


# WebSocket 连接事件
@socketio.on('connect')
def handle_connect():
    print('Client connected')


# WebSocket 断开连接事件
@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')


# 聊天消息事件
@socketio.on('message')
def handle_message(data):
    print('Received message:', data)
    emit('message', data, broadcast=True)


# 聊天室进入事件
@socketio.on('join_room')
def handle_join_room(data):
    room = data['room']
    join_room(room)
    emit('message', f'User {data["username"]} joined room {room}', room=room)


# 聊天室离开事件
@socketio.on('leave_room')
def handle_leave_room(data):
    room = data['room']
    leave_room(room)
    emit('message', f'User {data["username"]} left room {room}', room=room)


# 初始化 SocketIO
def init_socketio(app):
    socketio.init_app(app)


# 启动应用程序
if __name__ == '__main__':
    from flask import Flask

    app = Flask(__name__)
    app.register_blueprint(chat_blue)

    # 初始化 SocketIO
    init_socketio(app)

    # 启动应用程序和 SocketIO 服务器
    socketio.run(app, debug=True)
